import web3Helper from '@/utils/web3';

class ContractService {
  constructor() {
    this.contract = null;
    this.contractInfo = null;
  }

  // 初始化合约
  // readOnly: 为 true 时只读模式，不需要钱包；为 false 时需要钱包签名
  async init(readOnly = false) {
    try {
      // 读取合约信息
      const contractModule = await import('@/contracts/CrowdfundingPlatform.json');
      this.contractInfo = contractModule.default || contractModule;
      
      if (!this.contractInfo || !this.contractInfo.address) {
        throw new Error('合约未部署，请先部署智能合约');
      }

      this.contract = web3Helper.initContract(
        this.contractInfo.address,
        this.contractInfo.abi,
        readOnly  // 传递只读标志
      );

      return this.contract;
    } catch (error) {
      console.error('合约初始化失败:', error);
      throw error;
    }
  }

  // 获取合约实例
  getContract() {
    if (!this.contract) {
      throw new Error('合约未初始化');
    }
    return this.contract;
  }

  // 创建众筹活动
  async launchCampaign(name, description, goal, duration, timeUnit) {
    const contract = this.getContract();
    const goalInWei = web3Helper.parseEther(goal);
    
    const tx = await contract.launch(name, description, goalInWei, duration, timeUnit);
    await tx.wait();
    return tx;
  }

  // 安全转换为数字（兼容 BigNumber 和普通数字）
  _toNumber(value) {
    if (typeof value === 'number') {
      return value;
    }
    if (value && typeof value.toNumber === 'function') {
      return value.toNumber();
    }
    return Number(value);
  }

  // 获取众筹活动详情
  async getCampaign(id) {
    const contract = this.getContract();
    const campaign = await contract.getCampaign(id);
    
    return {
      creator: campaign.creator,
      name: campaign.name,
      description: campaign.description,
      goal: web3Helper.formatEther(campaign.goal),
      pledged: web3Helper.formatEther(campaign.pledged),
      startAt: this._toNumber(campaign.startAt),
      endAt: this._toNumber(campaign.endAt),
      claimed: campaign.claimed
    };
  }

  // 获取众筹状态（增强版，前端判断）
  async getCampaignStatus(id) {
    const contract = this.getContract();
    const campaign = await contract.getCampaign(id);
    
    const now = Math.floor(Date.now() / 1000);
    const startAt = this._toNumber(campaign.startAt);
    const endAt = this._toNumber(campaign.endAt);
    const pledged = parseFloat(web3Helper.formatEther(campaign.pledged));
    const goal = parseFloat(web3Helper.formatEther(campaign.goal));
    
    // 状态判断逻辑
    // 1. 未开始
    if (now < startAt) {
      return 'Not Started';
    }
    
    // 2. 进行中（严格小于结束时间）
    if (now < endAt) {
      return 'Active';
    }
    
    // 3. 已结束的情况
    // 3.1 达到或超过目标 -> 成功
    if (pledged >= goal) {
      return 'Successful';
    }
    
    // 3.2 无投资 -> 取消
    if (pledged === 0) {
      return 'Cancelled';
    }
    
    // 3.3 有投资但未达标 -> 失败
    return 'Failed';
  }

  // 投资众筹
  async pledge(id, amount) {
    const contract = this.getContract();
    const amountInWei = web3Helper.parseEther(amount);
    
    const tx = await contract.pledge(id, { value: amountInWei });
    await tx.wait();
    return tx;
  }

  // 取消投资
  async unpledge(id) {
    const contract = this.getContract();
    const tx = await contract.unpledge(id);
    await tx.wait();
    return tx;
  }

  // 提取资金（创建者）
  async claim(id) {
    const contract = this.getContract();
    const tx = await contract.claim(id);
    await tx.wait();
    return tx;
  }

  // 申请退款
  async refund(id) {
    const contract = this.getContract();
    const tx = await contract.refund(id);
    await tx.wait();
    return tx;
  }

  // 取消众筹活动
  async cancelCampaign(id) {
    const contract = this.getContract();
    const tx = await contract.cancelCampaign(id);
    await tx.wait();
    return tx;
  }

  // 获取用户投资金额
  async getPledgedAmount(campaignId, userAddress) {
    const contract = this.getContract();
    const amount = await contract.pledgedAmount(campaignId, userAddress);
    return web3Helper.formatEther(amount);
  }

  // 获取用户创建的众筹
  async getUserCreatedCampaigns(userAddress) {
    const contract = this.getContract();
    const ids = await contract.getUserCreatedCampaigns(userAddress);
    return ids.map(id => this._toNumber(id));
  }

  // 获取用户支持的众筹
  async getUserBackedCampaigns(userAddress) {
    const contract = this.getContract();
    const ids = await contract.getUserBackedCampaigns(userAddress);
    // 去重
    const uniqueIds = [...new Set(ids.map(id => this._toNumber(id)))];
    return uniqueIds;
  }

  // 获取所有众筹ID
  async getAllCampaignIds() {
    const contract = this.getContract();
    const ids = await contract.getAllCampaignIds();
    return ids.map(id => this._toNumber(id));
  }

  // 获取众筹总数
  async getCampaignCount() {
    const contract = this.getContract();
    const count = await contract.count();
    return this._toNumber(count);
  }
}

export default new ContractService();

